package viettravel.guiandevent;

import org.holoeverywhere.app.ProgressDialog;
import org.json.JSONException;
import org.json.JSONObject;

import viettravel.DTO.DBCommunication;
import viettravel.DTO.JSONParser;
import viettravel.common.Constants;
import viettravel.guiandevent.R;
import viettravel.guiandevent.map.GooglemapV2Activity;
import viettravel.guiandevent.map.GooglemapV2GetLatLngActivity;
import viettravel.guiandevent.place.ListPlaceFavorite;
import viettravel.guiandevent.place.NewPlaceActivity;
import viettravel.guiandevent.search.PlaceSearch;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;

public class ViettravelMainActivity extends BaseSlidingMenuLeft {

	private ProgressDialog mProgressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main_page);
		setTheme(Constants.THEME);

		Constants.CONTEXT = ViettravelMainActivity.this;
		Constants.TYPEFACE_CAVIAR = Typeface.createFromAsset(this.getAssets(),
				"fonts/utm_caviar.ttf");
		Constants.TYPEFACE_NYALA = Typeface.createFromAsset(this.getAssets(),
				"fonts/utm_nyala.ttf");
		// Customization ActionBar
		 
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setIcon(R.drawable.ic_back_arrow);
		actionBar.setBackgroundDrawable(Constants.APP_DRAWABLE);
		//Define left sliding menu

		setBehindContentView(R.layout.layout_menu_provinces_fragment);
		FragmentTransaction fragmentTransaction = getSupportFragmentManager()
				.beginTransaction();
		fragmentTransaction.add(R.id.sliding_list_provinces,
				new MenuProvincesFragment());
		fragmentTransaction.commit();

		//Customization left sliding menu

		this.setSlidingActionBarEnabled(true);
		getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
		getSlidingMenu()
				.setShadowDrawable(R.drawable.customview_sliding_shadow);
		getSlidingMenu().setBehindOffsetRes(R.dimen.actionbar_home_width);
		getSlidingMenu().setBehindScrollScale(0.25f);

		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu _menu) {
		SubMenu subMenuSort = _menu.addSubMenu(this
				.getString(R.string.main_submenu_header));
		subMenuSort.add(Menu.NONE, R.id.main_subitem_addplace, Menu.NONE,
				this.getString(R.string.main_submenu_addplace)).setIcon(
				R.drawable.ic_add);
		subMenuSort.add(Menu.NONE, R.id.main_subitem_favorite, Menu.NONE,
				this.getString(R.string.main_submenu_favorite)).setIcon(
				R.drawable.ic_favorit);
		subMenuSort.add(Menu.NONE, R.id.main_subitem_google, Menu.NONE,
				this.getString(R.string.main_submenu_google)).setIcon(
				R.drawable.ic_google_map);
		subMenuSort.add(Menu.NONE, R.id.main_subitem_search, Menu.NONE,
				this.getString(R.string.main_submenu_search)).setIcon(
				R.drawable.ic_search);
		subMenuSort.add(Menu.NONE, R.id.main_subitem_information, Menu.NONE,
				this.getString(R.string.main_submenu_infomation)).setIcon(
				R.drawable.ic_information);
		/*subMenuSort.add(Menu.NONE, R.id.main_subitem_guide, Menu.NONE,
				this.getString(R.string.main_submenu_guide)).setIcon(
				R.drawable.ic_guide);*/

		MenuItem menuItemSort = subMenuSort.getItem();
		menuItemSort.setIcon(R.drawable.ic_list_w);
		menuItemSort.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return super.onCreateOptionsMenu(_menu);
	}

	public void loginFaceBook() {
		mProgressDialog = new ProgressDialog(ViettravelMainActivity.this,
				ProgressDialog.THEME_HOLO_LIGHT);
		mProgressDialog.setMessage(getString(R.string.loadingdata));
		mProgressDialog.setCancelable(true);
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.show();
		Session.openActiveSession(this, true, new Session.StatusCallback() {
			@Override
			public void call(Session session, SessionState state,
					Exception exception) {
				if (session.isOpened()) {
					Request.executeMeRequestAsync(session,
							new Request.GraphUserCallback() {
								@Override
								public void onCompleted(GraphUser _user,
										Response response) {
									mProgressDialog.dismiss();
									Log.v(Constants.TAG, "come here");
									Log.v(Constants.TAG, _user.getUsername());
									if (_user != null) {
										Constants.CURRENT_FACEBOOK_USER = _user;
										postUser(_user.getId(), _user.getName());
										Log.v(Constants.TAG,
												Constants.CURRENT_FACEBOOK_USER
														.getName());
										new SyncData()
												.execute(Constants.CURRENT_FACEBOOK_USER
														.getId());
									}
								}
							});
				}
				if (mProgressDialog.isShowing())
					mProgressDialog.dismiss();
			}
		});
	}

	public void postUser(String userId, String userName) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_RESULT, 1);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject json = new JSONParser().makeUserJson(
				Constants.CURRENT_FACEBOOK_USER.getId(),
				Constants.CURRENT_FACEBOOK_USER.getName());
		new PostData().execute(jsonObject, json);

	}

	public class PostData extends AsyncTask<JSONObject, Void, Boolean> {

		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(ViettravelMainActivity.this,
					ProgressDialog.THEME_HOLO_LIGHT);
			mProgressDialog.setMessage("Post data...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected void onPostExecute(Boolean result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}
		}

		@Override
		protected Boolean doInBackground(JSONObject... params) {
			int type = 0;
			try {
				type = params[0].getInt(Constants.TAG_RESULT);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (type == 1)
				return DBCommunication.postData(Constants.ROOT,
						Constants.SUFFIX_POST_USER, params[1]);
			else
				return false;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	/**
	 * Item is selected
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home: {
			toggle();
			return true;
		}
		case R.id.main_subitem_favorite: {
			if (Constants.CURRENT_FACEBOOK_USER != null) {
				postUser(Constants.CURRENT_FACEBOOK_USER.getId(),
						Constants.CURRENT_FACEBOOK_USER.getName());
				new SyncData().execute(Constants.CURRENT_FACEBOOK_USER.getId());
			} else
				loginFaceBook();
			return true;
		}
		case R.id.main_subitem_addplace: {
			Intent intent = new Intent(ViettravelMainActivity.this,
					NewPlaceActivity.class);
			startActivity(intent);
			return true;
		}
		case R.id.main_subitem_search: {
			Intent intent = new Intent(ViettravelMainActivity.this,
					PlaceSearch.class);
			startActivity(intent);
			return true;
		}
		case R.id.main_subitem_information: {
			Intent intent = new Intent(ViettravelMainActivity.this,
					InformationActivity.class);
			startActivity(intent);
			return true;
		}

		case R.id.main_subitem_google: {
			Intent intent = new Intent(ViettravelMainActivity.this,
					GooglemapV2Activity.class);
			startActivity(intent);
			return true;
		}

		case R.id.main_subitem_guide: {
			Intent intent = new Intent(ViettravelMainActivity.this,
					GooglemapV2GetLatLngActivity.class);
			startActivity(intent);
			return true;
		}

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public class SyncData extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(ViettravelMainActivity.this,
					ProgressDialog.THEME_HOLO_LIGHT);
			mProgressDialog.setMessage(getString(R.string.loadingdata));
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected String doInBackground(String... params) {
			JSONParser jsonParser = new JSONParser();
			JSONObject jsonRoot = jsonParser.getJSONFromUrl(Constants.ROOT
					+ Constants.SUFFIX_GET_FAVORITEPLACE + params[0]);
			return jsonRoot.toString();
		}

		@Override
		protected void onPostExecute(String result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
				Intent intent = new Intent(ViettravelMainActivity.this,
						ListPlaceFavorite.class);
				intent.putExtra("FAVORITE", result);
				startActivity(intent);
			}
		}
	}
}
